<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%
    String basePath=request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+request.getContextPath()+"/";
%>
<html>
<head>
    <base href="<%=basePath%>">
    <!--引入jquery-->
    <script type="text/javascript" src="jquery/jquery-1.11.1-min.js"></script>
    <!--引入echarts插件-->
    <script type="text/javascript" src="jquery/echarts/echarts.min.js"></script>

    <script src="static/lib/echarts/echarts.min.js"></script>
    <script type="text/javascript" src="static/js/echarts-gl.min.js"></script>
    <script type="text/javascript" src="static/echatrs/echarts.min.js"></script>
    <style>
        /* 父容器布局 */
        .container {
            display: flex;
            gap: 30px;
            padding: 20px;
            max-width: 1200px;
            margin: 0 auto;
            height: 100vh; /* 新增：让容器占满视口高度 */
        }

        #line {
            width: 550px;
            height: 620px;
            border: 1px solid #eaeaea;
            border-radius: 8px;
            background-color: #fff;
            display: flex;
            flex-direction: column;
        }

        /* 新增：滚动条样式美化 */
        #analysisPanel::-webkit-scrollbar {
            width: 8px;
        }

        #analysisPanel::-webkit-scrollbar-thumb {
            background-color: #ccc;
            border-radius: 4px;
        }

        #analysisPanel::-webkit-scrollbar-track {
            background-color: #f5f5f5;
        }

        .toggle-btn {
            position: sticky; /* 新增：按钮始终可见 */
            top: 20px;
            z-index: 2;
        }

        #conclusions {
            flex: 1;
            padding: 0 0 20px 20px;
            overflow-y: auto;
            position: relative;
            max-width: none; /* 移除原有限制 */
            margin-left: 0;
            margin-right: -8px;
        }

        /* 滚动条样式调整 */
        #conclusions::-webkit-scrollbar {
            width: 8px;
            background: transparent;
        }
        #conclusions::-webkit-scrollbar-thumb {
            border-radius: 4px 0 0 4px; /* 左侧圆角 */
        }

        /* 新增：内容区域最大宽度 */
        #conclusions {
            max-width: 500px;
            margin-left: auto;
        }

        /*新增*/
        #analysisPanel {
            flex-grow: 1;
            background: #fff;
            border-radius: 12px;
            padding: 0; /* 移除全局padding */
            height: 620px;
            display: flex; /* 新增 */
            flex-direction: column; /* 新增 */
            box-shadow: 0 4px 12px rgba(0,0,0,0.08);
        }

        /* 按钮样式优化 */
        #AIBtn {
            position: sticky;
            top: 10px;
            background: #1890ff;
            color: white;
            border: none;
            padding: 10px 24px;
            border-radius: 25px;
            cursor: pointer;
            font-weight: 500;
            transition: all 0.3s ease;
            box-shadow: 0 2px 8px rgba(24,144,255,0.2);
            z-index: 20;
            margin-bottom: 12px;
        }

        #AIBtn:hover {
            background: #40a9ff;
            transform: translateY(-1px);
            box-shadow: 0 4px 12px rgba(24,144,255,0.3);
        }

        /* 结论区域优化 */
        #conclusions {
            margin-top: 0;
            padding-top: 20px;
            position: relative;
            z-index: 10;
        }

        #conclusions h3 {
            position: static;
            margin: 0 0 15px;
            padding: 15px 0;
            border-bottom: 2px solid #1890ff;
        }

        .conclusion-item {
            background: #f8faff;
            padding: 18px;
            border-radius: 8px;
            margin-bottom: 15px;
            line-height: 1.6;
            color: #4a4a4a;
            border: 1px solid #e8f4ff;
            transition: transform 0.2s ease;
        }

        .conclusion-item:hover {
            transform: translateX(5px);
        }

        .conclusion-item strong {
            color: #1890ff;
            font-weight: 600;
        }

        /* 滚动条美化 */
        #analysisPanel::-webkit-scrollbar {
            width: 6px;
        }

        #analysisPanel::-webkit-scrollbar-thumb {
            background: rgba(24,144,255,0.3);
            border-radius: 4px;
        }

        #analysisPanel::-webkit-scrollbar-track {
            background: rgba(240,240,240,0.5);
        }

        /* 关键数据强调 */
        .conclusion-item hr {
            border: 0;
            height: 1px;
            background: linear-gradient(90deg, transparent, #1890ff, transparent);
            margin: 15px 0;
        }

        /* 响应式调整 */
        @media (max-width: 768px) {
            #analysisPanel {
                padding: 15px;
            }

            .conclusion-item {
                padding: 12px;
            }
        }

        /* 新增调整 */
        #conclusions {
            margin-top: 15px;
            margin-left: 0; /* 取消自动边距 */
            padding-left: 20px; /* 添加内边距控制间距 */
            max-width: 500px;
        }

        #conclusions h3 {
            margin-top: 0; /* 取消标题顶部外边距 */
            position: sticky; /* 固定标题位置 */
            top: 20px; /* 与按钮对齐 */
            z-index: 1; /* 确保标题在内容上方 */
            background: #fff; /* 添加背景色 */
            padding-right: 10px; /* 防止内容溢出遮挡 */
        }

        /* 为分析面板添加相对定位 */
        #analysisPanel {
            position: relative; /* 新增 */
        }

        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }

        /* 禁用按钮样式 */
        #AIBtn[disabled] {
            opacity: 0.7;
            cursor: not-allowed;
        }

        .top {
            padding: 20px 20px 0;
            position: sticky;
            top: 0;
            background: white;
            z-index: 100;
            box-shadow: 0 8px 12px -8px rgba(255,255,255,0.9); /* 滚动时显示下阴影 */
        }
        /* 分隔线装饰 */
        .top::after {
            content: '';
            position: absolute;
            bottom: 0;
            left: 20px;
            right: 20px;
            height: 1px;
            background: #eaeaea;
            opacity: 0.5;
        }

        /* 移动端适配 */
        @media (max-width: 768px) {
            .top {
                margin-bottom: 16px;
                padding-bottom: 12px;
            }

            #AIBtn {
                margin-bottom: 8px;
            }
        }
        /* 输入区域样式 */
        .input-group {
            display: flex;
            gap: 10px;
            margin-top: 1px;
            position: relative;
        }

        #aiInput {
            flex: 1;
            padding: 12px 45px 12px 15px;
            border: 1px solid #e0e0e0;
            border-radius: 25px;
            resize: none;
            min-height: 46px;
            max-height: 120px;
            line-height: 1.5;
            transition: all 0.3s ease;
        }

        #aiInput:focus {
            border-color: #1890ff;
            box-shadow: 0 0 8px rgba(24,144,255,0.2);
        }

        /* 加载动画样式 */
        .loading-spinner {
            width: 40px;
            height: 40px;
            border: 4px solid #f3f3f3;
            border-top: 4px solid #3498db;
            border-radius: 50%;
            animation: spin 1s linear infinite;
            margin-bottom: 10px;
        }
        .loading-text {
            color: #666;
            font-size: 14px;
        }
    </style>
    <title>市场活动统计图表</title>
    <script type="text/javascript">
        // 保存数据
        var old_data;
        var question;
        $(function () {
            // 初始化时加载会话存储
            const savedConclusion = sessionStorage.getItem('analysisConclusion');
            if (savedConclusion) {
                updateConclusion(savedConclusion);
            }
            // 初始化时加载本地存储
            // const savedConclusion = localStorage.getItem('analysisConclusion');
            // if (savedConclusion) {
            //     updateConclusion(savedConclusion);
            // }
            //发送查询请求
            $.ajax({
                url: 'getActivityChart',
                type: 'post',
                dataType: 'json',
                success: function (data) {
                    old_data = data.retData;
                    console.log(old_data)
                    // 基于准备好的dom，初始化echarts实例
                    var myPieChart = echarts.init(document.getElementById('line'));
                    // 指定图表的配置项和数据
                    myPieChart.setOption({
                        tooltip: {
                            trigger: 'axis'
                        },
                        legend: {
                            data: ['关联的线索数量', '关联的联系人数量']
                        },
                        xAxis: [{
                            type: 'category',
                            data: data.retData.map(item => item["市场活动名称"]), // 动态获取活动名称
                            axisLabel: {
                                interval: 0,
                                rotate: 45
                            }
                        }],
                        yAxis: [{
                            type: 'value',
                            name: '数量'
                        }],
                        series: [{
                            name: '关联的线索数量',
                            type: 'line',
                            data: data.retData.map(item => item["关联的线索数量"]) // 动态获取线索数据
                        },{
                            name: '关联的联系人数量',
                            type: 'line',
                            data: data.retData.map(item => item["关联的联系人数量"]) // 动态获取联系人数据
                        }]
                    })
                }
            });

            // 点击按钮调 AI 接口
            $("#AIBtn").click(function (){
                // 先清空历史数据（显示上）
                $("#conclusions").empty();
                // 获取输入框内容并赋值给question
                question = $("#aiInput").val().trim();

                var $btn = $(this);
                $btn.prop('disabled', true);

                // 添加消息气泡和加载动画
                const userMessage = `
                    <div class="message user">
                        <div class="message-content">${question}</div>
                    </div>`;
                const loadingMessage = `
                    <div class="message bot">
                        <div class="message-content">
                            <div class="loading-spinner"></div>
                            <div class="loading-text">深度思考中...</div>
                        </div>
                    </div>`;

                $("#conclusions").append(userMessage + loadingMessage);

                $.ajax({
                    url:'activitiByAi',
                    data: {
                        content_data: JSON.stringify(old_data),
                        question:question
                    },
                    type:'post',
                    dataType:'json',
                    complete: function() {
                        $('#analysisPanel .loading-overlay').remove();
                        $btn.prop('disabled', false);
                    },
                    success: function (data) {
                        if (data.code === "1") {
                            // 保存到本地存储
                            // localStorage.setItem('analysisConclusion', data.retData);
                            sessionStorage.setItem('analysisConclusion', data.retData);
                            updateConclusion(data.retData);
                        } else {
                            console.error('AI分析失败:', data.message);
                            $('#conclusions').html('<div class="conclusion-item">分析失败: '+ data.message +'</div>');
                        }
                    },
                });
            });
            function updateConclusion(apiResponse) {
                const $conclusions = $('#conclusions');

                // 确保处理的是字符串类型
                if (typeof apiResponse !== 'string') {
                    console.error('无效的响应格式:', apiResponse);
                    $conclusions.html('<div class="conclusion-item">分析数据格式错误</div>');
                    return;
                }

                // 处理Markdown格式内容
                let formattedText = apiResponse
                    .replace(/###\s*/g, '<hr>') // 将###转换为分割线
                    .replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>') // 处理加粗
                    .replace(/\n/g, '<br>'); // 处理换行

                // 安全插入HTML
                $conclusions.empty().html(formattedText ||
                    '<div class="conclusion-item">未获取到有效分析数据</div>');

            }
            // 回车监听
            $("#aiInput").keypress(function(e) {
                if(e.which == 13 && !e.shiftKey) { // 回车键且没有按shift
                    e.preventDefault();
                    $("#AIBtn").click(); // 触发按钮点击
                }
            });
        });
    </script>
</head>
<body>

    <!-- 保持原有图表容器ID -->
    <div class="container">
        <div id="line"></div>

        <!-- 保持原有分析面板ID -->
        <div id="analysisPanel">
            <div class="top">
                <button id="AIBtn" class="toggle-btn">智能分析</button>
                <div class="input-group">
                    <textarea id="aiInput" placeholder="请输入您的问题（Shift+Enter换行）" class="form-control"></textarea>
                </div>
            </div>
            <div id="conclusions">
                <h3 style="color: #1890ff; margin-top: 0;">分析结论</h3>
                <div class="conclusion-item">

                </div>
            </div>
        </div>
    </div>

</body>
</html>
